package action

import (
	"MessageSendService/app/api/internal/process"
	"MessageSendService/app/common/log"
	models2 "MessageSendService/app/common/models"
	"fmt"
	"go.uber.org/zap"
	"strconv"
	"strings"
)

type AssambleAction struct {
	messageServiceI messageServeceI
}

func NewAssambleAction(i messageServeceI) *AssambleAction {
	return &AssambleAction{
		messageServiceI: i,
	}
}

// 解决循环依赖问题通过接口引入
type messageServeceI interface {
	BatchGet(ids []int) (v []models2.MessageTemplate, err error)
}

// Process 根据id查询模板信息，根据MessageParam[]填充TaskInfo参数
func (a *AssambleAction) Process(ctx *process.ProcessContext) error {

	log.GetLogger().Info("开始拼接参数.....")

	//根据id查询模版信息
	template, err := a.messageServiceI.BatchGet([]int{int(ctx.ProcessModel.MessageTemplateId)})
	if err != nil {
		return err
	}
	if len(template) == 0 {
		return fmt.Errorf("找不到对应的模版信息")
	}
	log.GetLogger().Info("查询到的模版信息：", zap.Any("template", template))
	var taskInfoList []models2.TaskInfo
	for _, v := range ctx.ProcessModel.MessageParam {
		sendAccount, err := strconv.ParseInt(template[0].Team, 10, 64)
		if err != nil {
			log.GetLogger().Error("转换失败", zap.Any("err", err))
		}
		taskInfoTemp := models2.TaskInfo{
			BusinessId:        template[0].Id,
			MessageTemplateId: template[0].Id,
			SendChannel:       template[0].SendChannel,
			SendAccount:       sendAccount, //           todo 发送账号 未来需要从其他地方获取
			MsgType:           template[0].MsgType,
			Receiver:          strings.Split(v.Receiver, ","),
			ContentModel:      v.Variables, // todo 这里要根据实际的消息渠道获取对应的models
			IdType:            template[0].IdType,
			TemplateType:      template[0].TemplateType,
			ShieldType:        template[0].ShieldType,
		}
		taskInfoList = append(taskInfoList, taskInfoTemp)
	}

	log.GetLogger().Info("", zap.Any("taskInfoList", taskInfoList))

	// 填充责任链的发送消息数据
	ctx.ProcessModel.TaskInfo = taskInfoList

	log.GetLogger().Info("拼接参数完成.....", zap.Any("taskInfoList", ctx.ProcessModel.TaskInfo))
	return nil
}
